package cn.middle.swap.portal;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.middle.common.basic.enums.Status;
import com.middle.common.result.ApiResponse;
import com.middle.common.result.Page;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.middle.basic.entity.SysMenu;
import cn.middle.basic.entity.SysRole;
import cn.middle.basic.service.SysMenuService;
import cn.middle.basic.service.SysRoleService;

/**
 * 角色管理
 * @author KING
 *
 */
@RequestMapping("/role")
@Controller
public class RoleController {
	
	private final static String PREFIX = "sys/role/";
	
	//private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private SysRoleService sysRoleService;
	
	@Autowired
	private SysMenuService menuService;
	
	@SaCheckPermission("role:add")
	@GetMapping("/add")
	public String add() {
		return PREFIX + "add";
	}
	
	@SaCheckPermission("role:add")
	@SuppressWarnings("unchecked")
	@ResponseBody
	@PostMapping("/add")
	public ApiResponse<String> add(@Valid SysRole role){
		if(sysRoleService.occupiedCode(role.getCode())) {
			return ApiResponse.FailCustomWithMessage(String.valueOf(-1000), "编码已被占用！");
		}
		role.setStatus(Status.Active.code());
		role.setCreateTime(new Date());
		role.setUpdateTime(new Date());
		sysRoleService.save(role);
		return ApiResponse.successWithData("添加角色成功");
	}
	
	@SaCheckPermission("role:edit")
	@GetMapping("/edit")
	public String edit(@NotNull(message="id不能为空！")Long id,ModelMap modelMap) {
		if(id == null) {
			throw new NullPointerException("传递参数为空！");
		}
		SysRole role = sysRoleService.getById(id);
		if(role == null) {
			throw new NullPointerException("角色信息不存在，请您刷新界面检查！");
		}
		modelMap.put("role", role);
		return PREFIX + "edit";
	}
	
	@SaCheckPermission("role:edit")
	@SuppressWarnings("unchecked")
	@ResponseBody
	@PostMapping("/edit")
	public ApiResponse<String> edit(@Valid SysRole role){
		
		if(role.getId() == null) {
			throw new NullPointerException("传递参数为空！");
		}
		
		SysRole sysRole = this.sysRoleService.getById(role.getId());
		
		if(sysRole == null) {
			throw new NullPointerException("角色信息不存在，请您刷新界面检查！");
		}
		
		if(!sysRole.getCode().equals(role.getCode())) { //编码不一致，检查是否已被占用
			if(sysRoleService.occupiedCode(role.getCode())) {
				return ApiResponse.FailCustomWithMessage(String.valueOf(-1000), "编码已被占用！");
			}
		}
		role.setUpdateTime(new Date());
		sysRoleService.update(role);
		return ApiResponse.successWithData("修改角色成功");
	}
	
	@SaCheckPermission("role:list")
	@GetMapping("/list")
	public String list(@RequestParam(value = "page", defaultValue = "1") Integer pageNum,
			@RequestParam(value="pageSize",defaultValue="10") Integer limit,
			String code,String name,ModelMap modelMap){
		Page<SysRole> roles = sysRoleService.listByCodeOrName(pageNum, limit, code, name);
	    modelMap.put("code", code);
	    modelMap.put("name", name);
		modelMap.put("pageInfo", roles);
		return PREFIX + "list";
	}
	
	/**
	 * 删除角色
	 * @param roleId
	 * @return
	 */
	@SaCheckPermission("role:delete")
	@SuppressWarnings("unchecked")
	@ResponseBody
	@GetMapping("/delete/{roleId}")
	public ApiResponse<String> delete(@PathVariable("roleId") Long roleId){
		boolean association = sysRoleService.hasAssociationRole(roleId);
		if(association) {
			return ApiResponse.FailCustomWithMessage(String.valueOf(-1000), "该角色已被用户关联，请您先解除关系再删除！");
		}
		sysRoleService.disarmPermissionsAndDelete(roleId);
		return ApiResponse.successWithData("删除成功！");
	}
	
	@SaCheckPermission("role:authorisation")
    @GetMapping("/permission")
    public String toRolePermission(@NotNull(message="角色id不能为空！")Long roleId, ModelMap modelMap){
    	List<SysMenu> menus = menuService.getAll();
    	List<Long> permissons = sysRoleService.associationRolePermissions(roleId);
    	
        modelMap.put("roleId", roleId);
        modelMap.put("treeNodeList", menus);
        StringBuilder builder = new StringBuilder();
        for(Long permissionId : permissons) {
        	builder.append(permissionId).append(",");
        }
        if(builder.length() > 0) builder.deleteCharAt(builder.length() - 1);
        modelMap.put("permissionIds", builder.toString());
        return PREFIX + "permission";
    }
	
	@SaCheckPermission("role:authorisation")
    @ResponseBody
    @PostMapping("/permission")
    public ApiResponse<String> rolePermission(@NotBlank(message = "角色ID不能为空！")Long roleId, @Size(message = "请至少选择一个", min = 1) Long[] permissionIds) {
    	List<Long> permissions = new ArrayList<>();
    	Collections.addAll(permissions, permissionIds);
        this.sysRoleService.associationRolePermissions(roleId, permissions);
    	return ApiResponse.successWithData("授权成功！");
    }

}
